package com.gws.ievent.config;

import com.gws.ievent.common.enums.EventTimeTypeEnum;
import com.gws.ievent.scheduler.Scheduler;
import com.gws.ievent.scheduler.IJob;
import com.gws.ievent.scheduler.Trigger;
import com.gws.ievent.service.job.PrintJob;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

import java.util.Random;

/**
 * @author song
 * @date 2022/10/20 22:19
 */
@Component
public class MockAddPrintJob implements ApplicationListener<ApplicationStartedEvent> {

    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {

        System.out.println("ApplicationStartedEvent------------------");
        Scheduler scheduler = newCycleEvent("*/1 * * * * *", new PrintJob("每1s打印一次"));
        //IEvent e2 = newCycleEvent("*/7 * * * * *", new PrintJob("每7s打印一次"));
        //IEvent e3 = newCycleEvent("*/15 * * * * *", new SleepJob(10, "每15s睡眠10s"));
        //IEvent e4 = newCycleEvent("*/8 * * * * *", new SleepJob(8, "每8s睡眠8s"));
        //IEvent e5 = newCycleEvent("*/3 * * * * *", new ThreadPoolMonitorJob(ThreadPoolExecutorInstance.INSTANCE.instance()));

        Trigger.getInstance().add(scheduler);
    }


    private Scheduler newCycleEvent(String cron, IJob job) {
        Scheduler e = new Scheduler();
        e.setId(new Random().nextLong());
        e.setName(job.getClass().getName());
        e.setTimeType(EventTimeTypeEnum.CYCLE.getValue());
        e.setTime(cron);
        e.setJob(job);

        return e;
    }

    private Scheduler newFixedEvent(String fixedTime, IJob job) {
        Scheduler e = new Scheduler();
        e.setName(job.getClass().getName());
        e.setTimeType(EventTimeTypeEnum.FIXED.getValue());
        e.setTime(fixedTime);
        e.setJob(job);

        return e;
    }

}
